package com.bjsxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bjsxt.domain.StorageTbl;
import com.bjsxt.mapper.StorageTblMapper;
import com.bjsxt.service.StorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    private StorageTblMapper storageTblMapper ;

    private static Logger logger = LoggerFactory.getLogger(StorageServiceImpl.class) ;


    @Transactional
    @Override
    public void deduct(String productNo, int count) {
        logger.info("开始扣减商品{}的库存，数量为{}",productNo,count);
        //1 查询数据库里面该商品的库存
        StorageTbl storageTbl = storageTblMapper.selectOne(new LambdaQueryWrapper<StorageTbl>()
                .eq(StorageTbl::getCommodityCode, productNo));
        if(storageTbl==null){
            throw new IllegalArgumentException("商品不存在") ;
        }
        // 2 扣减操作
        int idleCount = storageTbl.getCount() - count ;

        if(idleCount< 0 ){
            throw  new RuntimeException("库存不足") ;
        }
        //3 设置到商品的库存里面
        storageTbl.setCount(idleCount);

        // 4 保存到数据库里面
        storageTblMapper.updateById(storageTbl) ;

        logger.info("扣减商品{}的库存成功，剩余的库存为{}" ,productNo, idleCount);
    }
}
